package com.lagou.zk;

import com.lagou.client.RPCConsumer;
import io.netty.channel.ChannelFuture;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;

/**
 * @author wuyuhan
 * @date 2021/1/13 11:15
 */
public class NodeListener implements PathChildrenCacheListener {
    public RPCConsumer rpcConsumer;

    public NodeListener(RPCConsumer rpcConsumer) {
        this.rpcConsumer = rpcConsumer;
    }

    @Override
    public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception {
        String path = event.getData().getPath();
        String data = new String(event.getData().getData());
        String[] ip_port = path.split(":");
        //String[] ip_port = data.split(":");
        //String key=ip_port[0]+":"+port_time[0];
        if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
            System.out.println("节点被创建" + path+",内容"+data);
            rpcConsumer.getKey_time().put(path,Integer.parseInt(data));
            rpcConsumer.start(ip_port[0],Integer.parseInt(ip_port[1]));
        }
        if (event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED) {
            System.out.println("节点被移除" + path+",内容"+data);
            if(rpcConsumer.getChannelHashMap().containsKey(path)){
                ChannelFuture future = rpcConsumer.getChannelHashMap().get(path);
                future.channel().disconnect();
                future.channel().close();
                System.out.println("断开服务器连接:"+path);
                rpcConsumer.getChannelHashMap().remove(path);
            }
            if(rpcConsumer.getKey_time().containsKey(path)){
                rpcConsumer.getKey_time().remove(path);
            }
        }
        if(event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED){
            System.out.println("节点被更新" + path+",内容"+data);
            rpcConsumer.getKey_time().put(path,Integer.parseInt(data));
        }
    }
}
